package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.TransfreCreateEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.CashierInputFilter;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import java.io.Serializable;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class TransferAccountsGroupActivity extends BaseSwipeBackActivity implements TextWatcher {

    private static final String TAG = TransferAccountsGroupActivity.class.getSimpleName();
    private static final int SELECTE_RESULT_USER = 10001;
//    @BindView(R.id.head_img)
//    ImageView headImg;
    @BindView(R.id.pre_v_back)
    ImageView backImg;

    @BindView(R.id.relative_select_per)
    RelativeLayout relative_select_per;
    @BindView(R.id.image_head)
    ImageView image_head;

    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.message)
    EditText message;

    @BindView(R.id.commit)
    Button commit;
    @BindView(R.id.tv_balance)
    TextView tvBalance ;
    private String moneyStr;
    private PasswordEditText payPSD;
    private AlertDialog payDialog;
//    private ImFriendEntivity friendInfo;
    private PGService mPGservice;
    private long destid = 0;
    private double balance;

    private String uids ;
    private String uheads ;

    @Override
    public int getContentViewId() {
        return R.layout.activity_transfer_accounts_group;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.transfer_accounts);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();
//        friendInfo = (ImFriendEntivity) getIntent().getSerializableExtra("friendInfo");
        destid = getIntent().getLongExtra("destid", 0);
        InputFilter[] filters = {new CashierInputFilter()};//限定输入为金额模式
        money.setFilters(filters);
//        friendInfo.setId(destid);
//        if (null != friendInfo) {
//            GlideUtils.loadCircleImage(getApplicationContext(), friendInfo.getHeadUrl(), headImg);
//            nickName.setText(friendInfo.getName());
//        }
        // 设置可输入小数
        money.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        money.addTextChangedListener(this);
        commit.setEnabled(false);
        mPGservice.getBalance(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.net_visit_exception));
            }

            @Override
            public void onNext(String s) {
                balance = Double.parseDouble(s);
                tvBalance.setText(getResources().getString(R.string.yu_e_1)+s+getResources().getString(R.string.yuan));
            }
        });
    }

    @OnClick({R.id.commit, R.id.pre_v_back, R.id.relative_select_per})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.commit:
                doCommit();
                break;
            case R.id.pay_cancel:
                payDialog.dismiss();
                break;
            case R.id.pay_commit:
                String pwd = payPSD.getText().toString().trim();
                if (null == pwd || "".equals(pwd)) {
                    new ToastUtils().showLongToast(getString(R.string.please_import_pay_psd));
                } else {
                    validatePayPwd(pwd);
                }
                break;
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.relative_select_per:
                Intent intent = new Intent(TransferAccountsGroupActivity.this, SelecteATFriendActivity.class);
//                intent.putExtra("tag", 12);
                intent.putExtra("groupId", ""+destid);
                intent.putExtra("tag", 13);
                startActivityForResult(intent, SELECTE_RESULT_USER);
                break;
        }
    }

    /**
     * 验证支付密码
     *
     * @param pwd
     */
    private void validatePayPwd(final String pwd) {
        final String payPsd = MD5.MD532(pwd);
        mPGservice.validatePayPwd(payPsd, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showLongToast(getResources().getString(R.string.pay_psd_approve_defeat));
            }

            @Override
            public void onNext(String validateEntivity) {
                String moneystr = money.getText().toString().trim();
                String liuyan = message.getText().toString().trim();
                if (null == liuyan && "".equals(liuyan)) {
                    liuyan = getString(R.string.wish_you_prosperity);
                }
                if (liuyan.length() > 10){
                    showToast("留言长度不能大于10");
                }
//                sendRedPacket(""+destid,money,liuyan);
//                doCommit();
//                createTransfer(liuyan, friendInfo.getId() + "", moneystr, payPsd);
                createTransfer(liuyan, uids + "", moneystr, payPsd, ""+destid);

                payDialog.dismiss();
            }
        });
    }

    /**
     * 转账给好友(群)
     */
    private void createTransfer(String msg, String destId, String amount, String payPwd, String groupId) {
        String userId=ToolsUtils.getMyUserId();
        com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("userId", userId);
        json.put("msg", msg);
        json.put("destId", destId);
        json.put("amount", amount);
        json.put("payPwd", payPwd);
        json.put("groupId", groupId);
        String content = RequestRSAUtils.setRsaContent(json);
        Log.i(TAG, "onResultError: -----ToolsUtils.getMyUserId()=" + ToolsUtils.getMyUserId() + "--destId=" + destId + "--amount=" + amount + "--payPwd" + payPwd);
        mPGservice.createTransfer(content).subscribe(new AbsAPICallback<TransfreCreateEntivity>() {
        //mPGservice.createTransfer(ToolsUtils.getMyUserId(), msg, destId, amount, payPwd, groupId).subscribe(new AbsAPICallback<TransfreCreateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.i(TAG, "onResultError: -----" + ex.getDisplayMessage());
                new ToastUtils().showLongToast("转账失败！");
            }

            @Override
            public void onNext(TransfreCreateEntivity validateEntivity) {
                new ToastUtils().showLongToast("转账成功！");
                Intent intent = new Intent();
                intent.putExtra("transfreCreate", (Serializable) validateEntivity);
                setResult(10, intent);
                finish();
            }
        });
    }

    /**
     * 这里做提交操作
     */
    private void doCommit() {
        final UserEntivity user = ToolsUtils.getUser();

        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        Long id = user.getId();
        mPGservice.getBalance(id + "").subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.e(TAG, "onResultError: 这里是转账的 获取余额 错误----");
            }

            @Override
            public void onNext(String s) {
                Float balance = Float.valueOf(s);
                hideProgress();
                Float moneyFl = Float.valueOf(money.getText().toString().trim());
                if (moneyFl > balance) {
                    showToast(getString(R.string.balance_lack_please_recharge));
                    startActivity(SelectRechargeTypeActivity.class);
                } else {
                    String payInfo = user.getPayInfo();
                    if (payInfo == null || "".equals(payInfo)) {
                        showToast(getString(R.string.please_set_pay_psd));
                        return;
                    }
                    showPayDialog();
                }
            }
        });
    }

    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        payDialog = new AlertDialog.Builder(this).setView(dialog).create();
        payDialog.show();
        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(this);
        payCommit.setOnClickListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if ("".equals(s.toString())) {
            commit.setText(getResources().getString(R.string.trans_ok));
            commit.setEnabled(false);
            commit.setBackgroundResource(R.drawable.bg_circle_btn_gray);
        } else {
            if (!"".equals(s.toString())&&Double.parseDouble(s.toString())>balance){
                commit.setText(getResources().getString(R.string.yue_nozu));
                commit.setEnabled(false);
                commit.setBackgroundResource(R.drawable.bg_circle_btn_gray);
            }else {
                commit.setText(getResources().getString(R.string.trans_ok));
                commit.setEnabled(true);
                commit.setBackgroundResource(R.drawable.bg_circle_btn);
            }

        }
    }

    private void popupKeyboard(final PasswordEditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case SELECTE_RESULT_USER :
                if (resultCode == RESULT_OK){
                    uids = data.getStringExtra("uids");
                    uheads = data.getStringExtra("uheads");
//                    atdatas = uheads.split(",");
//                    initAtHead();

                    if (null!=uheads && !TextUtils.isEmpty(uheads)){
                        GlideUtils.loadCircleImage(TransferAccountsGroupActivity.this, uheads, image_head);
                    }

                }
                break;
        }
    }

}
